<?php


namespace TbfExcel;


class ExcelData {
    private $grid = null;
    private $array2d = null;

    /**
     * @param $grid
     * @return ExcelData
     */
    static function fromGrid(array $grid){
        $obj = new ExcelData();
        $obj->grid = $grid;
        return $obj;
    }

    /**
     * @param $array2d
     * @return ExcelData
     */
    static function from2D(array $array2d){
        $obj = new ExcelData();
        $obj->array2d = $array2d;
        return $obj;
    }

    /**
     * @return array|null
     */
    function toGrid(){
        if ($this->grid!=null){
            return $this->grid;
        }
        return self::TitleArrayToGrid($this->array2d);
    }

    /**
     * @return array|null
     */
    function to2D(){
        if ($this->array2d!=null){
            return $this->array2d;
        }
        return self::GridToTitleArray($this->grid);
    }

    private static function TitleArrayToGrid($data){
        if (count($data)<=1){
            return array();
        }
        $output = array();
        $titleList = $data[0];
        for($i=1;$i<count($data);$i++){
            $j=0;
            $thisRow = array();
            foreach($titleList as $key){
                if (empty($data[$i][$j])){
                    $thisRow[$key] = '';
                }else {
                    $thisRow[$key] = $data[$i][$j];
                }
                $j++;
            }
            $output[] = $thisRow;
        }
        return $output;
    }
    private static function GridToTitleArray($grid){
        if (empty($grid)){
            return array();
        }
        $output = array();
        $titleList = array_keys($grid[0]);
        $output[] = $titleList;
        foreach($grid as $row){
            $thisRow = array();
            foreach($titleList as $key){
                if (!isset($row[$key])){
                    $thisRow[] = null;
                    continue;
                }
                $thisRow[] = $row[$key];
            }
            $output[] = $thisRow;
        }
        return $output;
    }
} 